package app

import (
	"context"
	"runtime/debug"

	"gitee.com/ddlin/kit/xlog"
	"gitee.com/ddlin/kit/xtrace"
	"gitee.com/ddlin/tiktok-go-tool/config"
	"gitee.com/ddlin/tiktok-go-tool/internal/router"
	"gitee.com/ddlin/tiktok-go-tool/service"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type App struct {
	Config       config.Config
	Engine       *gin.Engine
	HttepSerivce *service.HttpService
	Router       *router.Router
	Ctx          context.Context
	Logger       *zap.Logger
}

func NewApp(
	config config.Config,
	engine *gin.Engine,
	httpService *service.HttpService,
	Router *router.Router,
	Ctx context.Context,
	Logger *zap.Logger,
) *App {
	return &App{
		Config:       config,
		Engine:       engine,
		Router:       Router,
		HttepSerivce: httpService,
		Ctx:          Ctx,
		Logger:       Logger,
	}
}

func InitCtx() (ctx context.Context) {
	//设置gc触发大小; GOGC 默认值是 100，也就是下次 GC 触发的 heap 的大小是这次 GC 之后的 heap 的一倍
	debug.SetGCPercent(125)
	return xtrace.NewCtxWithTraceId(context.Background())
	//return context.Background()
}

func InitGin(cfg config.Config) (r *gin.Engine) {
	gin.SetMode(cfg.Mode)
	return gin.New()
}

func InitHttpService(cfg config.Config) *service.HttpService {
	return service.NewHttpService(cfg.HttpClient)
}

// ProvideLogger Log提供者
func ProvideLogger(cfg config.Config) (*zap.Logger, func(), error) {
	conf := cfg.XLogger
	conf.ServiceName = cfg.Name
	logger, err := xlog.New(conf)
	sync := func() {
		_ = logger.Sync()
	}
	return logger, sync, err
}
